<?php

namespace app\api\controller;

use think\Config;
use fast\Http;

use app\common\controller\Api;
use app\api\model\Room as RoomModel;
use app\api\model\Game as GameModel;

/**
 * 房间管理
 */
class Room extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 新建房间
     *
     */
    public function createRoom()
    {

        $param =  $this->request->post();
        $game_kind = $param['game_kind'];//游戏标识
        
        $game = GameModel::detail(['game_kind'=>$game_kind]);
        if (!$game){
            $this->error('找不到游戏');
        }
        $userinfo = $this->auth->getUserinfo();
        $balance = $param['config']['balance'];
        if (!$this->verify($userinfo,$balance)){
            $this->error('钻石不足');
        }

        $data = [
            'roomId' => $this->createRoomID(),
            'game_id' => $game['id'],
            'user_id' => $this->auth->id,
            'play_count' => $game['play_count'],
            'balance' => $balance,
            'room_pay_type' => $param['config']['room_pay_type'],
            'room_type' => $param['room_type'],
            'game_json' => json_encode($param['config']),
        ];
        
        // $ret = Http::get('http://127.0.0.1:8000/createRoom', $data);
        // if (!$ret){
        //     $this->error('游戏服务未开启');
        // }

        $roomModel = new RoomModel;
        $roominfo = $roomModel->createRoom($data);
        if ($roominfo){
            $this->success('返回成功', ['roomInfo'=>$roominfo,'gameInfo'=>$game]);
        }
        $this->error('房间创建失败');
    }


    /**
     * 验证是否合法
     */
    private function verify($userinfo,$balance)
    {
        $roomModel = new RoomModel;
        $max_balance = $roomModel->where(['user_id' => $userinfo['id'],'state' => 0])->sum('balance');

        return $userinfo['money'] - $max_balance >= $balance;
    }

    /**
     * 生成房间号，6位数
     */
    private function createRoomID()
    {
        $roomid = rand(0,9) . '' . rand(10000,99999);
        $room = RoomModel::detail(['roomId'=>$roomid]);
        if ($room){
            return $this->createRoomID();
        }
        return $roomid;
    }
    
}
